package cn.hzc.fortess.system.eventbus;

import cn.hzc.fortess.core.common.HttpContext;
import cn.hzc.fortess.core.common.constant.Const;
import cn.hzc.fortess.core.shiro.ShiroKit;
import cn.hzc.fortess.system.service.SettingService;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailSubscriber {

    private static final Logger log = LoggerFactory.getLogger(MailSubscriber.class);

    @Autowired
    JavaMailSender mailSender;
    @Autowired
    SettingService settingService;

    @Value("${spring.mail.username}")
    String mailFrom;


    @Subscribe
    public void sendMail(UserPwdChangeEvent event) {
        log.info("收到用户密码变更的事件...您的{}新密码为 {}", event.getUser().getAccount(), event.getNewpwd());

        if (StringUtils.isBlank(mailFrom) || StringUtils.isBlank(event.getUser().getEmail())) {
            return;
        }
        if (!checkConfigMailbox()) {
            return;
        }

        sendPwdChangeMail(event);

    }


    private boolean checkConfigMailbox() {

        final JavaMailSenderImpl javaMailSender = ((JavaMailSenderImpl) mailSender);

        if (StringUtils.isBlank(javaMailSender.getHost())
                || StringUtils.isBlank(javaMailSender.getUsername())
        ) {
            log.warn("邮箱信息未配置,新密码无法发送至用户邮箱.");
            return false;
        }
        return true;
    }

    /**
     * 使用网易的邮箱时，授权的邮箱必须与发送的邮箱一致
     * 其他邮箱待验证
     */
    public void sendPwdChangeMail(UserPwdChangeEvent event) {

        final String to = event.getUser().getEmail();

        log.info("发送邮件...To {}", to);


        final String mailTemplate = settingService.getValByKey("MAIL_TEMPLATE_PWD");
        String content = "您的密码为 " + event.getNewpwd();
        if (StringUtils.isNotBlank(mailTemplate)) {
            content = mailTemplate.replace("${newpwd}", event.getNewpwd());
            content = content.replace("${account}", event.getUser().getAccount());
//            content = content.replace("${systemName}", Const.DEFAULT_SYSTEM_NAME);
        }
        final String subject = "【u8ma】系统登录信息";

        try {
            MimeMessage message = this.mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            this.mailSender.send(message); //邮箱配置错误可能卡住

            EventExecute.me().post(new BizLogEvent("发送邮件",
                    ShiroKit.getUser().getAccount(), HttpContext.getIp(), "已送达:" + event.getUser().getEmail(), null, null));
            log.info("用户密码变更,发送邮件成功 {}", event.getUser().getEmail());
        } catch (Exception e) {
            log.error("用户密码变更,发送邮件失败：{},to :{}", e.getMessage(), event.getUser().getEmail());
            EventExecute.me().post(new BizLogEvent("发送邮件",
                    ShiroKit.getUser().getAccount(), HttpContext.getIp(), e));
        }


    }
}
